import json
import sys

import requests
import re
import hashlib
import main
from lxml import etree
'''
抓取课表
'''

globalflag=1
class get():
    host = r'http://jxglstu.hfut.edu.cn'
    username = ''
    password = ''
    studentId = ''
    semesterId = ''
    bizTypeId = ''
    session = requests.session()

    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.studentId=""
        self.semesterId = ''
        self.bizTypeId = ''

    def login(self):        # 登录
        print("login.......")
        print("flag==",globalflag)
        print("username=",self.username)
        print("passworde=",self.password)
        self.studentId=""
        self.semesterId = ''
        self.bizTypeId = ''
        try:
            salt = self.session.get('{host}/eams5-student/login-salt'.format(host=self.host)).text
            data = {
                'username': self.username,
                'password': hashlib.sha1((salt + '-' + self.password).encode('utf-8')).hexdigest(),
                                                        # 密码加密 生成salt串+password串
                'captcha': ''
            }
            self.session.post(url='{host}/eams5-student/login'.format(host=self.host), json=data)
            return self
        except:
            print("登陆失败0，请确认教务系统能正常访问")
            data={"info":"登陆失败0，请确认教务系统能正常访问"}
            main.callback(data)
            return self
    def set(self):
        print("set.......")
        print("flag==",globalflag)
        try:
            self.studentId=""
            self.semesterId = ""
            self.bizTypeId = ""
            result = self.session.get('{host}/eams5-student/for-std/course-table'.format(host=self.host))
            self.semesterId = re.search(r'(?<=<option selected="selected" value=")\d+', result.text)[0]
            self.studentId = re.search(r'(?<=var studentId = )\d+', result.text)[0]
            self.bizTypeId = re.search(r'(?<=bizTypeId: )\d+', result.text)[0]
            print("self.studentId =",self.studentId)
            data={"success":"登陆成功"}
            main.callback(data)
            return self
        except Exception as e:
            print("err", e)
            print("登陆失败1，请检查账号密码,或者稍后再尝试登陆")
            data={"info":"登陆失败1，请检查账号密码,或者稍后再尝试登陆"}
            main.callback(data)
            self.session.get('{host}/eams5-student/logout-emitter'.format(host=self.host))
            self.session.close()
            print("退出登陆")
            return self


    def get_lesson(self):
        print("get_lesson.......")
        print("flag==",globalflag)
        params = {
            'bizTypeId': self.bizTypeId,
            'semesterId': self.semesterId,
            'dataId': self.studentId
        }
        lessonIds = self.session.get(url='{host}/eams5-student/for-std/course-table/get-data'.format(host=self.host),
                               params=params).json()['lessonIds']
        data = {'lessonIds': lessonIds, 'studentId': self.studentId, 'weekIndex': ''}
        datum = self.session.post(url='{host}/eams5-student/ws/schedule-table/datum'.format(host=self.host),
                            json=data).json()
        print("get lesson success")
        main.callback(str(datum))
        self.session.get('{host}/eams5-student/logout-emitter'.format(host=self.host))
        self.session.close()
        print("退出登陆")

    def getUserdata(self):
        print("getUser_data.......")
        print("flag==",globalflag)
        try:
            url00='{host}/eams5-student/for-std/student-info/info/'+str(self.studentId)
            result1 = self.session.get(url00.format(host=self.host))

            def decodeData(templist):
                templist00=[]
                for i in templist:
                    i_bytes = etree.tostring(i, encoding='utf-8')
                    i = i_bytes.decode('utf-8')
                    i=i.replace(" ", "")
                    i=i.replace("<dt>", "")
                    i=i.replace("</dt>", "")
                    i=i.replace("<strong>", "")
                    i=i.replace("</strong>", "")
                    i=i.replace("<span>", "")
                    i=i.replace("</span>", "")
                    i=i.replace("<dd>", "")
                    i=i.replace("</dd>", "")
                    i=i.replace("<dd/>", "")
                    i=i.replace("\n", "")
                    templist00.insert(-1,i)
                return templist00

            html = etree.HTML(result1.content, parser=etree.HTMLParser(encoding='utf8'))
            content_bytes = html.xpath('//div[@id="base-info"]')[0]
            print("--------------------------------")
            baseInfo_key= content_bytes.xpath('//strong')
            baseInfo_value = content_bytes.xpath('//span')
            detailInfo_list_dt = content_bytes.xpath('//dt')
            detailInfo_list_dd = content_bytes.xpath('//dd')
            #bytes值转为正常string
            baseInfo0=decodeData(baseInfo_key)
            baseInfo1=decodeData(baseInfo_value)
            detailInfo0=decodeData(detailInfo_list_dt)
            detailInfo1=decodeData(detailInfo_list_dd)

            tempjsonlist=[]
            for i in range(0,int(len(baseInfo0)/4+1)):
                jsondata={
                    baseInfo0[i-1]:baseInfo1[(2*i)]
                }
                print(jsondata)
                tempjsonlist.append(jsondata)

            print("----------------------------------------------------------------")
            for i in range(0,20):
                jsondata={
                    detailInfo0[i]:detailInfo1[i]
                }
                print(jsondata)
                tempjsonlist.append(jsondata)
            #data2 =json.dumps(tempjsonlist, indent=4, separators=(',', ':')).encode('utf-8').decode('raw_unicode_escape')
            #data={"data":tempjsonlist}
            main.callback(str(tempjsonlist))
            self.session.get('{host}/eams5-student/logout-emitter'.format(host=self.host))
            self.session.close()
            print("退出登陆")
        except Exception as e:
            print("err", e)
            data={"info":"登陆失败，请检查账号密码,或者稍后再尝试登陆"}
            print(data)
            main.callback(data)
        self.session.get('{host}/eams5-student/logout-emitter'.format(host=self.host))
        self.session.close()
        print("退出登陆")

    def logout(self):
        result0 = self.session.get('{host}/eams5-student/logout-emitter'.format(host=self.host))
        self.session.close()
        print("退出登陆")

def showData():
    with open("course.json", "r", encoding="utf-8") as f:
        user_data = json.load(f)
    result = user_data['result']
    lessonList = result['lessonList']
    scheduleList = result['scheduleList']
    scheduleGroupList = result['scheduleGroupList']

    lessonName = { lesson0['id']: lesson0['courseName'] for lesson0 in lessonList}
    print(lessonName)
    print("----------------------------")
    sss = []
    for l_obj1 in scheduleList:

        if l_obj1["weekIndex"]==5:

            print(lessonName[l_obj1["lessonId"]],end=",")
            print(l_obj1["personName"],end=",")
            print(l_obj1["date"],end=",")
            print("周"+str(l_obj1["weekday"]))

            for day in range(1,7):
                if l_obj1["weekday"] ==day:
                    print(day)


            rtjson={l_obj1["lessonId"]:
                        {
                            "courseName":lessonName[l_obj1["lessonId"]],
                            "teacher":l_obj1["personName"],
                            "date":l_obj1["date"],
                            "starttime":l_obj1["startTime"],
                            "weekday":l_obj1["weekday"],
                            "position":l_obj1["room"]["nameZh"],
                        }
                    }


            sss.append(rtjson)
            with open("thisweek.json", "w", encoding="utf-8") as f:
                js_data = json.dumps(sss, indent=4, separators=(',', ':')).encode('utf-8').decode(
                    'raw_unicode_escape')
                f.write(js_data)

    with open("thisweek.json", "r", encoding="utf-8") as f:
        user_data0 = json.load(f)
    main.callback(user_data0)


def checkacc(useracc,passwd):  # 登录
    host = r'http://jxglstu.hfut.edu.cn'
    session = requests.session()
    try:
        salt = session.get('{host}/eams5-student/login-salt'.format(host=host)).text
        data = {
            'username': useracc,
            'password': hashlib.sha1((salt + '-' + passwd).encode('utf-8')).hexdigest(),
            # 密码加密 生成salt串+password串
            'captcha': ''
        }
        session.post(url='{host}/eams5-student/login'.format(host=host), json=data)
        print("success")
        return "success"
    except Exception as e:
        print("err",e)
        return "error"






if __name__ == '__main__':
    #username = input('请输入您的学号：')
    #password = input('请输入您的密码：')
    username = "2018211832"
    password = "Gyx@1074"

    #get(username, password).login().set().get_lesson()
    #get(username, password).login().set().get_lesson()
    #showData()
    try:
        get(username, password).login().set().getUserdata()
    except Exception as e:
        print("err00",e)
    #根据日期获取周次
    #获取该周次的所有课程信息
